from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from utils.tencent.cos import get_credential_demo, delete_one
from web import models
from web.form.file import FileModelForm


@csrf_exempt
def file(request,project_id):
    """ file页面（展示数据） """
    parent_obj = None # 先判断是否携带文件id，没有则认为是根目录，有则认为是这个id下的目录
    if request.GET.get("file_id"):
        parent_obj = models.FileRepository.objects.filter(id=request.GET.get("file_id"),project=request.manage).first()

    # GET用来生成页面目录
    if request.method == "GET":
        # 查出所有根目录
        data_list = models.FileRepository.objects.filter(project=request.manage,parent__isnull=True).order_by("id","-file_type")
        if parent_obj: # 当携带文件夹id则认为进入了这个id的文件夹里，展示父级id为这个id的文件和文件夹数据
            # 生成当前文件路径
            path_list = []
            while parent_obj:
                path_list.append(parent_obj)
                parent_obj = parent_obj.parent
            path_list.reverse()

            data_list = models.FileRepository.objects.filter(project=request.manage,parent_id=request.GET.get("file_id")).order_by("id","-file_type")
            form = FileModelForm()
            return render(request, 'file.html',{"form":form,"data_list":data_list,"path_list":path_list})
        else: # 当没携带文件夹id则认为展示根目录数据
            form = FileModelForm()
            return render(request, 'file.html',{"form":form,"data_list":data_list, 'folder_object': parent_obj})

    # post用来保存文件夹
    fid = request.POST.get("fid")
    print(fid)
    file_obj = None
    if fid:
        file_obj = models.FileRepository.objects.filter(id=fid,project=request.manage).first()
    print(request.POST)
    form = FileModelForm(data=request.POST,instance=file_obj)
    if form.is_valid():
        form.instance.parent = parent_obj
        form.instance.file_type = 2
        form.instance.project = request.manage
        form.instance.update_user = request.transaction.user
        form.save()
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,"errors":form.errors})

@csrf_exempt
def delete(request,project_id):
    # 以下是数据库删除
    fid = request.POST.get("fid")
    del_obj = models.FileRepository.objects.filter(id=fid).first()
    if del_obj.file_type ==1:
         request.manage.use_space += del_obj.file_size # 当执行删除的为文件时，直接删除并将项目空间还回去
         request.manage.save()
         models.FileRepository.objects.filter(id=fid).delete()
        # cos删除
         delete_one(bucket=request.manage.bucket, region=request.manage.region, Key=del_obj.key)

    file_list = []
    total_size = 0
    file_list.append(del_obj)# 此时代表执行删除的是文件夹，将文件夹加进循环列表，进行查找下面的所有文件和文件夹
    for item in file_list:
        son_list = models.FileRepository.objects.filter(parent=item)
        for row in son_list:
            if row.file_type ==1:
                total_size += row.file_size
                models.FileRepository.objects.filter(id=row.id).delete()
                # cos删除
                delete_one(bucket=request.manage.bucket, region=request.manage.region, Key=row.key)
            elif row.file_type ==2:
                file_list.append(row)
    request.manage.use_space += total_size
    request.manage.save()
    models.FileRepository.objects.filter(id=fid).delete()# 上面的各类操作完了之后对当前文件夹直接删除
    return JsonResponse({"status":True})

@csrf_exempt
def get_cors_token(request,project_id):
    bucket = request.manage.bucket
    result = get_credential_demo(bucket=bucket,region='ap-chengdu')
    print(result)
    return JsonResponse({'status': True, 'data': result})